package com.vision.core.cl.ui;

import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.widget.core.client.container.CardLayoutContainer;

/**
 * Responsible for showing the appropriate panel based on the {@link Place} specified
 * in the URL. 
 * 
 * @author Mark
 * 
 */
public class MainViewImpl implements MainView {

	private Presenter presenter;

	private CardLayoutContainer parentPanel;
	
	private ITabItemPanelBuilder builder;

	public MainViewImpl(ITabItemPanelBuilder builder) {
		this.builder = builder;
		
//		tabPanel = new TabPanel();
//		tabPanel.setBodyBorder(true);
//		tabPanel.setTabScroll(true);
//		tabPanel.setCloseContextMenu(true);
//		tabPanel.setLayoutData(new MarginData(5));
//
//		tabPanel.addSelectionHandler(new SelectionHandler<Widget>() {
//			@Override
//			public void onSelection(SelectionEvent<Widget> event) {
//				// Update the URL when a tab is activated/selected
//				Widget item = event.getSelectedItem();
//				if (item instanceof ITabItemPanel) {
//					ITabItemPanel t = (ITabItemPanel) item;
//					presenter.goTo(new AppPlace(t.getPanelId()));
//				}
//			}
//		});
		
		parentPanel = new CardLayoutContainer();
	}
	
	@Override
	public Widget asWidget() {
		return parentPanel;
	}
	
	@Override
	public void openTab(String id) {
		if (id == null || id.isEmpty())
			return;
		
		// Check if the TabItemPanel is already existing
		ITabItemPanel panel = findPanel(id);

		if (panel != null) {
			// Just activate the tab
			parentPanel.setActiveWidget(panel);
		} else {
			// Create the tab item panel and add to the tabPanel
			builder.create(id, parentPanel);
		}
	}
	
	@Override
	public String getBusyMesssage() {
		ITabItemPanel panel = (ITabItemPanel) parentPanel.getActiveWidget();
		return panel == null ? null : panel.getBusyMessage();
	}
	
	/**
	 * Returns the {@link ITabItemPanel} with the specified <tt>id</tt>.
	 * 
	 * @param id
	 * @return
	 */
	protected ITabItemPanel findPanel(String id) {
		for (int i = 0; i <  parentPanel.getWidgetCount(); i++) {
			ITabItemPanel panel = (ITabItemPanel) parentPanel.getWidget(i);
			if (id.equals(panel.getPanelId()))
				return panel;
		}
		return null;
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

}
